package com.wenx.concurrent;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 并发同步器--共享模式
 * 银行窗口同步类
 * Created by wenx on 2019-10-09 14:26
 */
public class BankServiceWindowShared {

    private final MySync sync;

    public BankServiceWindowShared(int count) {
        this.sync = new MySync(count);
    }

    private class MySync extends AbstractQueuedSynchronizer {

        MySync(int count) {
            setState(count);
        }

        @Override
        public int tryAcquireShared(int interval) {
            for (;;) {
                int current = getState();
                int newCount = current - 1;
                if (newCount < 0 || compareAndSetState(current,newCount))
                    return newCount;
            }
        }

        @Override
        public boolean tryReleaseShared(int interval) {
            for (;;) {
                int current = getState();
                int newCount = current + 1;
                if (compareAndSetState(current,newCount))
                    return true;
            }
        }

    }

    public void handle() {
        sync.acquireShared(1);
    }

    public void unHandle() {
        sync.releaseShared(1);
    }

}